package com.example.keepmesafe.service;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESCrypto {

	private final String ALGORITHM = "AES"; 
    private byte[] keyValue = new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' }; 

    public void setKeyValue(byte[] phrase) {
		this.keyValue = phrase;
	}


	public String getALGORITHM() {
            return ALGORITHM;
    }

    public byte[] getKeyValue() {
            return keyValue;
    } 
    
    private Key generateKey() throws Exception { 
        Key key = new SecretKeySpec(keyValue, ALGORITHM);
        return key; 
    }
    
	public String encrypt(String decryptedPassword) throws Exception {
		 Key key = generateKey(); 
         Cipher c = Cipher.getInstance(getALGORITHM()); 
         c.init(Cipher.ENCRYPT_MODE, key); 
         byte[] encValue = c.doFinal(decryptedPassword.getBytes()); 
         String encryptedValue = Base64.encode(encValue); 
         return encryptedValue;
	}

	public String decrypt(String encryptedValue) throws Exception {
		Key key = generateKey(); 
        Cipher c = Cipher.getInstance(getALGORITHM()); 
        c.init(Cipher.DECRYPT_MODE, key); 
        byte[] decordedValue = Base64.decode(encryptedValue); 
        byte[] decValue = c.doFinal(decordedValue); 
        String decryptedValue = new String(decValue); 
        return decryptedValue; 
	}
}
